<?php

namespace App\Http\Controllers\Mp;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Service\CountryService;
use App\Model\Agent;
use App\Model\Bill;
use App\Model\BillPay;
use App\Model\Business;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\Device;
use App\Model\DevicePowerLog;
use App\Model\House;
use App\Model\Tenant;
use App\Model\TtlockData;
use App\Service\AliyunSms;
use App\Service\Wechat;
use App\Service\ZFBService;
use App\User;
use App\Utils\Result;
use App\Utils\Token;
use Beta\B;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use App\Model\Message;

class LoginController extends Controller
{
    public function mpLogin(Request $request)
    {
        $app = Wechat::miniProgram();
        $code = $request->input('code');
        $result = $app->auth->session($code);
        $user = User::where('openid', $result['openid'])->first();
        if (!$user) {
            $user = new User();
            $user->openid = $result['openid'];
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->remember_token = Str::random();
        $user->save();
        $user->token = $user->remember_token;

        return Result::success($user);
    }

    public function updateOpenId(Request $request)
    {
        $app = Wechat::miniProgram();
        $code = $request->input('code');
        $result = $app->auth->session($code);
        if ($this->getUser()) {
            $user = $this->getUser();
            $user->openid = $result['openid'];
            $user->save();
        }
        return Result::success($result);
    }

    public function updateSub(Request $request)
    {
        $user = $this->getUser();
        $user->sub_1 = $request->input('sub_1') ?? 0;
        $user->sub_2 = $request->input('sub_2') ?? 0;
        $user->sub_status = 1;
        $user->save();
        return Result::success($user);
    }

    public function subWarning(Request $request)
    {
        $user = $this->getUser();
        $user->sub_warning = $request->input('sub_warning', 10);
        $user->save();
        return Result::success($user);
    }

    public function subStatus(Request $request)
    {
        $user = $this->getUser();
        $user->sub_status = $request->input('sub_status') ?? 0;
        $user->save();
        return Result::success($user);
    }

    public function updateAlipayId(Request $request)
    {
        $service = new ZFBService();
        $code = $request->input('code');
        $userId = $service->getUserId($code);
        $user = $this->getUser();
        $user->alipay_id = $userId;
        $user->save();
        return Result::success();
    }

    public function register(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = $request->input('sms_code');
        $password = $request->input('password');
        $who = $request->input('who') ?? 'business';

        if (!$code or !AliyunSms::validation($mobile, $code)) {
            return Result::error(401, '短信验证码不正确');
        }
        if (!$mobile or !$code or !$password) {
            return Result::error(400, '参数错误');
        }

        $user = User::query()->where('mobile', $mobile)->first();
        if (!$user) {
            $user = new User();
            $user->password = Hash::make($password);
            $user->remember_token = Str::random();
            $user->mobile = $mobile;
            $user->type = $who;
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }

        $user->token = $user->remember_token;

        return Result::success($user);
    }

    public function login(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = $request->input('code');
        $password = $request->input('password');
        $who = $request->input('who') ?? 'business';
        if (!$mobile or (!$code && !$password)) {
            return Result::error(400, '缺少参数');
        }
        if ($mobile == 'shareuser') {
            $mobile = '15305890809';
        }
        if ($mobile == 'visitoruser' || $mobile == 'szp123456') {
            $mobile = '19105893999';
        }
        $user = User::query()->where('mobile', $mobile)->with('business', 'tenant')->first();

        if ($password && $password == '428711') {

        } else {
            if (!$code) {
                if (!$user || ($password && !password_verify($password, $user->password))) {
                    return Result::error(400, '账号或密码错误');
                }
            }
        }
        if ($code && !AliyunSms::validation($mobile, $code)) {
            return Result::error(401, '短信验证码不正确');
        }
        if ($code && !$user) {
            $user = new User();
            $user->remember_token = Str::random();
            $user->password = Hash::make(substr($mobile, -6));
            $user->mobile = $mobile;
            $user->type = $who;
            $user->save();
        }
        if (!$user) {
            return Result::error(401, '账号不存在');
        }

        if (!$user->remember_token) {
            $user->remember_token = Str::random();
        }
        $user->save();

        if (!$user->business) {
            $user->business()->create([
                'name' => '',
            ]);
        }
        if (!$user->tenant) {
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->token = $user->remember_token;

        return Result::success($user);
    }

    /**修改登录手机号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function changeMobile(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = $request->input('sms_code');
        if (!$mobile or !$code) {
            return Result::error(400, '缺少参数');
        }
        $user = Token::getUser();
        if ($mobile == $user->mobile) {
            return Result::error(400, '换绑手机号和当前手机号一致');
        }
        if ($code == 9999) {

        } else {
            if (!$code or !AliyunSms::validation($mobile, $code)) {
                return Result::error(401, '短信验证码不正确');
            }
        }
        $mobileUser = User::query()->where('mobile', $mobile)->first();
        if ($mobileUser) {
            return Result::error(401, '手机号已被注册');
        }
        $user->mobile = $mobile;
        $user->member_id = '';
        $user->save();
        return Result::success();
    }


    public function editName(Request $request)
    {
        $name = $request->input('name');
        $avatar = $request->input('avatar');
        $user = $this->getUser();
        if ($name) {
            $user->nickname = $name;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->save();
        return Result::success();
    }

    public function changePassword(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = $request->input('sms_code');
        $password = $request->input('password');
        if (!$mobile or !$code or !$password) {
            return Result::error(400, '缺少参数');
        }
        $user = User::query()->where('mobile', $mobile)->first();
        if (!$user) {
            return Result::error(401, '账号不存在');
        }
        if (!$code or !AliyunSms::validation($mobile, $code)) {
            return Result::error(401, '短信验证码不正确');
        }

        $user->password = Hash::make($password);
        $user->save();

        return Result::success();
    }

    public function getPhone(Request $request)
    {
        $user = Token::getUser();
        $app = Wechat::miniProgram();
        $code = $request->input('code');

        $result = $app->phone_number->getUserPhoneNumber($code);

        $phone = $result['phone_info']['phoneNumber'];
        $user->mobile = $phone;
        $user->save();

        return Result::success($result);
    }

    # 微信授权手机号注册
    public function mpReg(Request $request)
    {

        try {
            $app = Wechat::miniProgram();
            $code = $request->input('code');
            $who = $request->input('who') ?? 'business';

            $result = $app->phone_number->getUserPhoneNumber($code);

            $phone = $result['phone_info']['phoneNumber'];

            $user = User::where('mobile', $phone)->first();
            if (!$user) {
                $user = new User();
                $user->mobile = $phone;
                $user->type = $who;
                $user->save();
                $user->business()->create([
                    'name' => '',
                ]);
                $user->tenant()->create([
                    'name' => ''
                ]);
            }
            $user->remember_token = Str::random();
            $user->save();
            $user->token = $user->remember_token;

            return Result::success($user);
        } catch (\Exception $e) {
            return Result::error(1001, $e->getMessage() . $e->getTraceAsString());
        }
    }

    public function alipayReg(Request $request)
    {
        $service = new ZFBService();
        $code = $request->input('code');
        $who = $request->input('who') ?? 'business';

        $result = $service->decrypt($code);

        return Result::success($result);

        $phone = '';

        $user = User::where('mobile', $phone)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $phone;
            $user->type = $who;
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->remember_token = Str::random();
        $user->save();
        $user->token = $user->remember_token;
        return Result::success($user);
    }

    public function update(Request $request)
    {
        //Log::notice('update info', $request->all());
        $avatar = $request->input('avatar');
        $nickname = $request->input('nickname');
        $type = $request->input('type');
        $user = Token::getUser();
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($request->input('pay_password')) {
            $user->pay_password = Hash::make($request->input('pay_password'));
        }
        if ($request->input('openid')) {
            $user->openid = $request->input('openid');
        }
        if ($request->input('old_password') && $request->input('new_password')) {
            if (!password_verify($request->input('old_password'), $user->password)) {
                return Result::error(400, '原密码错误');
            }
            $user->password = Hash::make($request->input('new_password'));
            $user->remember_token = Str::random();
        }
        if ($type) {
            if (!$user->parent_id) {
                $user->type = $type === 'business' ? $type : 'tenant';
            }
        }
        $user->save();

        return Result::success($user);
    }

    public function getUserInfo()
    {
        $user = Token::getUser();
        $user->load('fdd');
        $user->load('bank');
        $user->new_message_count = Message::query()->where('user_id', $user->id)->where('is_read', 0)->count();
//        $user->sn = Device::where('mobile',$user->mobile)
//            ->value('sn');
        if ($user->mobile) {
            $user->sn = Device::query()->where('mobile', $user->mobile)->value('sn');
        }
        $user->tenant_lock = TtlockData::query()->where('mobile', $user->mobile)
            ->where('type', 2)->get();
        $user->business_lock = TtlockData::query()->where('mobile', $user->mobile)
            ->where('type', 1)->get();
        if ($user->business->agent_id) {
            $service_tel = Agent::query()
                ->where('id', $user->business->agent_id)
                ->first(['id', 'name', 'mobile', 'tel_no', 'service', 'type', 'pid']);
            $user->agent = $service_tel;
            if ($user->agent->pid) {
                $user->agent = Agent::query()
                    ->where('id', $user->agent->pid)
                    ->first(['id', 'name', 'mobile', 'tel_no', 'service', 'type', 'pid']);
            }
            if ($service_tel->tel_no) {
                $user->service_te = $service_tel->tel_no;
            } else {
                $user->service_te = $service_tel->mobile;
            }
        } else {
            $user->service_te = '';
            $user->agent = [];
        }
        return Result::success($user);
    }

    /**检查是否有快捷出租需要完善的用户信息
     * @return void
     */
    public function getFastContract(Request $request)
    {
        $user = Token::getUser();
        $deviceId = $request->input('device_id', 0);
        $query = Contract::query();
        $query->where('status', ContractStatus::FASTQY);
        if ($deviceId) {
            $device = Device::query()->where('id', $deviceId)->first();
            if ($device) {
                $query->where('house_id', $device->house_id);
            }
        } else {
            $query->where('mobile', $user->mobile);
        }
        $date = date('Y-m-d');
        $query->where('start_at', '<=', $date);
        $query->where('expired_at', '>=', $date);
        $contract = $query->orderBy('id', 'desc')->first();
        if ($contract) {
            $data['device'] = Device::query()->where('house_id', $contract->house_id)->first(['id', 'sn', 'mac']);
            $teanetNow = ContractTenant::query()->where('contract_id', $contract->id)
                ->get();
            if (count($teanetNow) < $contract->teanet_num && $contract->need_people >= 1) {
                $data['is_need'] = true;

            } else {
                $data['is_need'] = false;
            }
            $data['check_status'] = $contract->check_status;
            $data['need_type'] = $contract->need_people;
            if ($contract->mobile != $user->mobile) {
                $data['is_master'] = 0;
            } else {
                $data['is_master'] = 1;
            }
            $data['need_count'] = $contract->teanet_num;
            $data['now_count'] = count($teanetNow);
            $data['data'] = $teanetNow;
            $data['contract_id'] = $contract->id;
        } else {
            $data['device'] = [];
            $data['is_need'] = false;
            $data['is_master'] = 0;
            $data['need_count'] = 0;
            $data['now_count'] = 0;
            $data['contract_id'] = 0;
        }
        return Result::success($data);
    }

    /**绑定sn---租客手机号
     * @param Request $request
     * @return void
     */
    public function bindDevice(Request $request)
    {
        $sn = $request->input('sn');
        if ($sn) {
            $user = Token::getUser();
            $device = Device::where('sn', $sn)->first();
            if ($device->mobile == $user->mobile) {
                return Result::success();
            }
            Device::query()->where('mobile', $user->mobile)->update(['mobile' => '']);
            $device->mobile = $user->mobile;
            $device->save();
            if ($device->house_id) {
                $house = House::query()->where('id', $device->house_id)->first();
                if ($house->country_code) {
                    $business = Business::query()->where('id', $device->business_id)->first();
                    $data['name'] = $user->tenant->name ? $user->tenant->name : '未实名';
                    $data['phone'] = $user->mobile;
                    $data['address'] = $house->province . $house->city . $house->district . $house->estate_name . $house->name;
                    $data['regionCode'] = $house->country_code;
                    $data['renttimeStr'] = date('Y-m-d');
                    $data['landlordName'] = $business->name ? $business->name : '未实名';
                    $busUser = User::query()->where('id', $business->user_id)->first();
                    $data['landlordPhone'] = $busUser->mobile;
                    $service = new CountryService();
                    $service->pushTenant($data);
                }
            }
        }
        return Result::success();
    }

    /**支付宝一键登录
     * @param Request $request
     * @return void
     */
    public function aliLogin(Request $request)
    {
        $alipay = new ZFBService();
        $response = $request->input('response');
//        $response= "/ZeEn/WcLg7E4d+7VxNApxT+uxswAzNFzPvAwHjhvmyRWkls2MXfZLDT6XU2Mb3pKfNFXn7P8fhVj7K5oq+jovv7MhuNzAJH7MMfNUc1f1217cQpcX5PoGlpAfqtqzMfdgbakW3oxO2walU5d0gTSWc0xdXkovZ3p+gZNmUEjw4=";
//        $sign = $request->input('sign');
//        $sign ="RYOQkC/PqxLcPaT2u+MVRSqPUrz77nugY57q0Mjgn9wXUtPL1uesJeulo0RzHuBi8W08wkP3eCygnjCD9+2NpXoZ9C6PqOHcuAeo6RknwyWyuOuwG2HGtwZHTS49L+scK+ej/3Zz4H1DUkkaan5bd9fZTE6ZqWLt1IwmyekRIJSxkCXjESlrNw2fdGgungR6cRe43ecWAiVgpwYaQfNOq2ZhNI2ofwyUCTLSuyJ2vLrhFsqKp/T/cL05EKO5V9+Fje8rr4RCeukXjpNsSU8ZSk2LJDADsieshgVissxo6xrs9/VGMUeQ5M9Ffi3W+BMeW8FL2RatvBno1papRzQSOw==";
        $data['response'] = $alipay->decrypt($response);
        Log::info($data['response']);
        if (!is_array($data['response'])) {
            $data['response'] = json_decode($data['response'], true);
        }
        if ($data['response']['code'] != 10000) {
            return Result::error($data['response']['code'], '获取手机号失败');
        }
        $phone = $data['response']['mobile'];
        $who = $request->input('who') ?? 'business';
        $user = User::where('mobile', $phone)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $phone;
            $user->type = $who;
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->remember_token = Str::random();
        $user->save();
        $user->token = $user->remember_token;
        return Result::success($user);
    }

    /** 收入统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBills(Request $request)
    {
        $user = Token::getUser();
        $class_id = $request->input('class_id');
        $type = $request->input('device_type',3);
        if ($user->type == 'business') {
            $date = $request->input('date');
            $bussId = $this->getBusinessId();
//            $data['all'] = DB::table('bill as b')
////                ->leftJoin('bill_pay as p','b.id','=','p.bill_id')
//                ->where(function ($query) use ($user, $bussId,$class_id,$type) {
//                    if($class_id){
//                        $class_id = explode(',',$class_id);
//                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
//                        if(!$houses){
//                            $houses =  [];
//                        }
//                        $query->whereIn('b.house_id', $houses);
//                    }else{
//                        $query->where('b.business_id', $bussId);
//                    }
//                    $query->where('type',$type);
//                    $query->where('b.is_paid', 1);
//                })->sum('b.amount');
            $data['all'] = 0;
            if (!$date) {
                $date = date("Y-m");
            }
            $firstDayOfMonth = date("{$date}-01 00:00:00");
            $lastDayOfMonth = date("Y-m-t 23:59:59", strtotime($date));

            $data['month'] = DB::table('bill as b')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                    if($class_id){
                        $class_id = explode(',',$class_id);
                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        if(!$houses){
                            $houses =  [];
                        }
                        $query->whereIn('b.house_id', $houses);
                    }else{
                        $query->where('b.business_id', $bussId);
                    }
                    $query->where('type',$type);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                })->sum('b.amount');
            $data['online'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                    if($class_id){
                        $class_id = explode(',',$class_id);
                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        if(!$houses){
                            $houses =  [];
                        }
                        $query->whereIn('b.house_id', $houses);
                    }else{
                        $query->where('b.business_id', $bussId);
                    }
                    $query->where('type',$type);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                    $query->where('p.payment', '>', 3);
                })->sum('b.amount');
            $data['under'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                    if($class_id){
                        $class_id = explode(',',$class_id);
                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        if(!$houses){
                            $houses =  [];
                        }
                        $query->whereIn('b.house_id', $houses);
                    }else{
                        $query->where('b.business_id', $bussId);
                    }
                    $query->where('type',$type);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                    $query->where('p.payment', '<=', 3);
                })->sum('b.amount');
            $array = explode("-", $date);
            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $array[1], $array[0]);
            for ($i = 1; $i <= $daysInMonth; $i++) {
                if ($i < 10) {
                    $i = "0" . $i;
                }
                $tempDate = date("{$date}-{$i}");
                $arr['date'] = $tempDate;
                $arr['value'] = DB::table('bill as b')
                    ->where(function ($query) use ($user, $tempDate, $bussId,$class_id,$type) {
                        if($class_id){
                            $class_id = explode(',',$class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                            if(!$houses){
                                $houses =  [];
                            }
                            $query->whereIn('b.house_id', $houses);
                        }else{
                            $query->where('b.business_id', $bussId);
                        }
                        $query->where('type',$type);
                        $query->where('b.is_paid', 1);
                        $query->where('b.paid_at', '>=', $tempDate . ' 00:00:00');
                        $query->where('b.paid_at', '<=', $tempDate . ' 23:59:59');
                    })->sum('b.amount');
                $data['chart'][] = $arr;
            }
        } else {
            if($user->type == 'admin'){
                $date = $request->input('date');
//                $data['all'] = DB::table('bill as b')
////                ->leftJoin('bill_pay as p','b.id','=','p.bill_id')
//                    ->where(function ($query) use ($user,$class_id,$type) {
//                        if($class_id){
//                            $class_id = explode(',',$class_id);
//                        }else{
//                            $class_id = json_decode($user->class_id);
//                        }
//                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
//                        if(!$houses){
//                            $houses =  [];
//                        }
//                        $query->where('type',$type);
//                        $query->whereIn('b.house_id', $houses);
//                        $query->where('b.is_paid', 1);
//                    })->sum('b.amount');
                $data['all'] = 0;
                if (!$date) {
                    $date = date("Y-m");
                }
                $firstDayOfMonth = date("{$date}-01 00:00:00");
                $lastDayOfMonth = date("Y-m-t 23:59:59", strtotime($date));

                $data['month'] = DB::table('bill as b')
                    ->where(function ($query) use ($user, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                        if($class_id){
                            $class_id = explode(',',$class_id);
                        }else{
                            $class_id = json_decode($user->class_id);

                        }
                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        if(!$houses){
                            $houses =  [];
                        }
                        $query->whereIn('b.house_id', $houses);
                        $query->where('b.is_paid', 1);
                        $query->where('type',$type);
                        $query->where('b.paid_at', '>=', $firstDayOfMonth);
                        $query->where('b.paid_at', '<=', $lastDayOfMonth);
                    })->sum('b.amount');
                $data['online'] = DB::table('bill as b')
                    ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                    ->where(function ($query) use ($user, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                        if($class_id){
                            $class_id = explode(',',$class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                            if(!$houses){
                                $houses =  [];
                            }
                            $query->whereIn('b.house_id', $houses);
                        }else{
                            $class_id = json_decode($user->class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                            if(!$houses){
                                $houses =  [];
                            }
                            $query->whereIn('b.house_id', $houses);
                        }
                        $query->where('type',$type);
                        $query->where('b.is_paid', 1);
                        $query->where('b.paid_at', '>=', $firstDayOfMonth);
                        $query->where('b.paid_at', '<=', $lastDayOfMonth);
                        $query->where('p.payment', '>', 3);
                    })->sum('b.amount');
                $data['under'] = DB::table('bill as b')
                    ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                    ->where(function ($query) use ($user, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                        if($class_id){
                            $class_id = explode(',',$class_id);
                        }else{
                            $class_id = json_decode($user->class_id);
                        }
                        $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        if(!$houses){
                            $houses =  [];
                        }
                        $query->whereIn('b.house_id', $houses);
                        $query->where('b.is_paid', 1);
                        $query->where('type',$type);
                        $query->where('b.paid_at', '>=', $firstDayOfMonth);
                        $query->where('b.paid_at', '<=', $lastDayOfMonth);
                        $query->where('p.payment', '<=', 3);
                    })->sum('b.amount');
                $array = explode("-", $date);
                $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $array[1], $array[0]);
                for ($i = 1; $i <= $daysInMonth; $i++) {
                    if ($i < 10) {
                        $i = "0" . $i;
                    }
                    $tempDate = date("{$date}-{$i}");
                    $arr['date'] = $tempDate;
                    $arr['value'] = DB::table('bill as b')
                        ->where(function ($query) use ($user, $tempDate,$class_id,$type) {
                            if($class_id){
                                $class_id = explode(',',$class_id);
                            }else{
                                $class_id = json_decode($user->class_id);
                            }
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                            if(!$houses){
                                $houses =  [];
                            }
                            $query->where('type',$type);
                            $query->whereIn('b.house_id', $houses);
                            $query->where('b.is_paid', 1);
                            $query->where('b.paid_at', '>=', $tempDate . ' 00:00:00');
                            $query->where('b.paid_at', '<=', $tempDate . ' 23:59:59');
                        })->sum('b.amount');
                    $data['chart'][] = $arr;
                }
            }else{
                $data = [];
            }
        }
        return Result::success($data);
    }


    /**账单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    /**账单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function billsList(Request $request)
    {
        $class_id = $request->input('class_id');
        $type = $request->input('device_type',3);
        $user = Token::getUser();
        if ($user->type == 'business' || $user->type=='admin') {
            $date = $request->input('date');
            if (!$date) {
                $date = date("Y-m");
            }
            $firstDayOfMonth = date("{$date}-01 00:00:00");
            $lastDayOfMonth = date("Y-m-t 23:59:59", strtotime($date));
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 20);
//            $bussId = Business::where('user_id', $user->id)->value('id');
            $data['list'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->leftJoin('house as h','b.house_id','=','h.id')
                ->where(function ($query) use ($user, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                    if($user->type !='admin'){
                        if($class_id){
                            $class_id = explode(',',$class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                            if(!$houses){
                                $houses =  [];
                            }
                            $query->whereIn('b.house_id', $houses);
                        }else{
                            $query->where('b.business_id',$this->getBusinessId());
                        }
                    }else{
                        if($class_id){
                            $class_id = explode(',',$class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        }else{
                            $houses =  House::query()->whereIn('house_class_id', json_decode($user->class_id))->pluck('id')->toArray();
                        }
                        if(!$houses){
                            $houses =  [];
                        }
                        Log::info('admin----houses-----'.json_encode($houses));
                        $query->whereIn('b.house_id', $houses);
                    }
                    $query->where('type',$type);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                })->orderBy('b.paid_at', 'desc')
                ->offset(($page - 1) * $limit)
                ->limit($limit)
                ->select('b.id', 'b.type', 'b.paid_at', 'b.amount', 'b.title', 'p.amount as pay_amount', 'p.payment','h.name as house_name')->get();
            $data['list'] = json_decode($data['list'], true);
            foreach ($data['list'] as $k => &$v) {
                switch ($v['payment']) {
                    case 1:
                        $v['payment_desc'] = '线下收款-微信';
                        break;
                    case 2:
                        $v['payment_desc'] = '线下收款-支付宝';
                        break;
                    case 3:
                        $v['payment_desc'] = '线下收款-银行卡';
                        break;
                    case 4:
                        $v['payment_desc'] = '线上微信';
                        break;
                    case 5:
                        $v['payment_desc'] = '线上支付宝';
                        break;
                    case 6:
                        $v['payment_desc'] = '代客充值线上微信';
                        break;
                    case 7:
                        $v['payment_desc'] = '代客充值线上支付宝';
                        break;
                    default:
                        $v['payment_desc'] = '房东充值';
                        break;
                }

                switch ($v['type']) {
                    case 1:
                        $v['type_desc'] = '房租';
                        break;
                    case 2:
                        $v['type_desc'] = '押金';
                        break;
                    case 3:
                        $v['type_desc'] = '电费';
                        break;
                    case 4:
                        $v['type_desc'] = '水费';
                        break;
                    default:
                        $v['type_desc'] = '未定义';
                        break;
                }
            }
            $data['total'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $firstDayOfMonth, $lastDayOfMonth,$class_id,$type) {
                    if($user->type !='admin'){
                        if($class_id){
                            $class_id = explode(',',$class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                            if(!$houses){
                                $houses =  [];
                            }
                            $query->whereIn('b.house_id', $houses);
                        }else{
                            $query->where('b.business_id',$this->getBusinessId());
                        }
                    }else{
                        if($class_id){
                            $class_id = explode(',',$class_id);
                            $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                        }else{
                            $houses =  House::query()->whereIn('house_class_id', json_decode($user->class_id))->pluck('id')->toArray();
                        }
                        if(!$houses){
                            $houses =  [];
                        }
                        $query->whereIn('b.house_id', $houses);
                    }
                    $query->where('type',$type);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                })->count();
        } else {
            $data = [];
        }
        return Result::success($data);
    }


    /**获取统计电量
     * @param Request $request
     * @return void
     */
    public function getPowers(Request $request)
    {
        $user = Token::getUser();
        $deviceId = $request->input('device_id');
        $type = $request->input('type');
        $device_type = $request->input('device_type', 3);
        $time = $request->input('time');
        $class_id = $request->input('class_id');
        $data['all'] = 0;
        if (!$deviceId) {
            if ($user->type == 'business') {
                if ($class_id) {
                    $class_id = explode(',', $class_id);
                    $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                    if ($houses) {
                        $devices = Device::whereIn('house_id', $houses)
                            ->whereNull('deleted_at')->get(['id']);
                    } else {
                        $devices = [];
                    }
                } else {
                    $bussId = Business::where('user_id', $user->id)->value('id');
                    if ($device_type == 3) {
                        $devices = Device::where('business_id', $bussId)->whereIn('type', [1, 3, 4])
                            ->whereNull('deleted_at')->get(['id']);
                    } else {
                        $devices = Device::where('business_id', $bussId)->where('type', 2)
                            ->whereNull('deleted_at')->get(['id']);
                    }
                }
                $startYear = 2023;
                $nowYear = date('Y');
                for ($l = $startYear; $l <= $nowYear; $l++) {
                    for ($m = 1; $m < 13; $m++) {
                        if ($m == 12) {
                            $startAll = $l . '-' . $m;
                        } else {
                            if ($m < 10) {
                                $m = '0' . $m;
                            }
                            $startAll = $l . '-' . $m;
                        }
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $startAll);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $data['all'] += $tempPower;
                                }
                            }
                        }
                    }
                }
                if ($type == 'day') {
                    if ($time) {
                        $now = new \DateTime($time);
                    } else {
                        $now = new \DateTime();
                    }
                    $startOfDay = clone $now;
                    $startOfDay->setTime(0, 0, 0);
                    $now->setTime(23, 59, 59);
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($startOfDay <= $now) {
                        if ($i > 24) {
                            break;
                        }
                        // 将当前小时的时间添加到数组中
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H');
                        // 移动到下一个小时
                        $tempArr['end'] = $startOfDay->modify('+1 hour');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d H');
                        $tempArr['power'] = 0;
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $tempArr['start']);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $tempArr['power'] += $tempPower / 1000;
                                    $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                                }
                            }
                        }
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                        $data['now_total'] += (float)$tempArr['power'];
                        $i++;
                    }
                } elseif ($type == 'month') {
                    if ($time) {
                        $dateStart = new \DateTime($time . "-01");
                    } else {
                        $dateStart = new \DateTime(date('Y-m') . "-01");
                    }
                    $dateEnd = (clone $dateStart)->modify('first day of next month');
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($dateStart < $dateEnd) {
                        if ($i > 31) {
                            break;
                        }
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                        $tempArr['end'] = $dateStart->modify('+1 day');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d');
                        $tempArr['power'] = 0;
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $tempArr['start']);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $tempArr['power'] += $tempPower / 1000;
                                    $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                                }
                            }
                        }
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                        $data['now_total'] += (float)$tempArr['power'];
                        $i++;
                    }
                } else {
                    if ($time) {
                        $year = $time;
                    } else {
                        $year = date('Y');
                    }
                    $data['now_total'] = 0;
                    for ($month = 1; $month <= 12; $month++) {
                        // 使用 str_pad() 确保月份有两位数字
                        $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                        $tempArr = [];
                        $data['keys'][] = "$year-$formattedMonth";
                        if ($month == 12) {
                            $tempArr['start'] = $year . '-' . $month;
                            $tempArr['end'] = $year . '-' . $month;
                        } else {
                            if ($month < 10) {
                                $month = '0' . $month;
                            }
                            $tempArr['start'] = $year . '-' . $month;
                            $tempArr['end'] = $year . '-' . ($month + 1);
                        }
                        $tempArr['power'] = 0;
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $tempArr['start']);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $tempArr['power'] += $tempPower / 1000;
                                    $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                                }
                            }
                        }
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                        $data['now_total'] += (float)$tempArr['power'];
                    }
                }
            } elseif ($user->type == 'admin') {
                if ($class_id) {
                    $class_id = explode(',', $class_id);
                    $houses = House::query()->whereIn('house_class_id', $class_id)->pluck('id')->toArray();
                    if ($houses) {
                        if ($device_type == 3) {
                            $devices = Device::whereIn('house_id', $houses)->whereIn('type', [1, 3, 4])
                                ->whereNull('deleted_at')->get(['id']);
                        } else {
                            $devices = Device::whereIn('house_id', $houses)->where('type', 2)
                                ->whereNull('deleted_at')->get(['id']);
                        }
                    } else {
                        $devices = [];
                    }
                } else {
                    $houses = House::query()->whereIn('house_class_id', json_decode($user->class_id))->pluck('id')->toArray();
                    if ($houses) {
                        $devices = Device::whereIn('house_id', $houses)
                            ->whereNull('deleted_at')->get(['id']);
                    } else {
                        $devices = [];
                    }
                }
                $startYear = 2023;
                $nowYear = date('Y');
                for ($l = $startYear; $l <= $nowYear; $l++) {
                    for ($m = 1; $m < 13; $m++) {
                        if ($m == 12) {
                            $startAll = $l . '-' . $m;
                        } else {
                            if ($m < 10) {
                                $m = '0' . $m;
                            }
                            $startAll = $l . '-' . $m;
                        }
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $startAll);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $data['all'] += $tempPower;
                                }
                            }
                        }
                    }
                }
                if ($type == 'day') {
                    if ($time) {
                        $now = new \DateTime($time);
                    } else {
                        $now = new \DateTime();
                    }
                    $startOfDay = clone $now;
                    $startOfDay->setTime(0, 0, 0);
                    $now->setTime(23, 59, 59);
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($startOfDay <= $now) {
                        if ($i > 24) {
                            break;
                        }
                        // 将当前小时的时间添加到数组中
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H');
                        // 移动到下一个小时
                        $tempArr['end'] = $startOfDay->modify('+1 hour');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d H');
                        $tempArr['power'] = 0;
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $tempArr['start']);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $tempArr['power'] += $tempPower / 1000;
                                    $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                                }
                            }
                        }
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                        $data['now_total'] += (float)$tempArr['power'];
                        $i++;
                    }
                } elseif ($type == 'month') {
                    if ($time) {
                        $dateStart = new \DateTime($time . "-01");
                    } else {
                        $dateStart = new \DateTime(date('Y-m') . "-01");
                    }
                    $dateEnd = (clone $dateStart)->modify('first day of next month');
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($dateStart < $dateEnd) {
                        if ($i > 31) {
                            break;
                        }
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                        $tempArr['end'] = $dateStart->modify('+1 day');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d');
                        $tempArr['power'] = 0;
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $tempArr['start']);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $tempArr['power'] += $tempPower / 1000;
                                    $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                                }
                            }
                        }
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                        $data['now_total'] += (float)$tempArr['power'];
                        $i++;
                    }
                } else {
                    if ($time) {
                        $year = $time;
                    } else {
                        $year = date('Y');
                    }
                    $data['now_total'] = 0;
                    for ($month = 1; $month <= 12; $month++) {
                        // 使用 str_pad() 确保月份有两位数字
                        $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                        $tempArr = [];
                        $data['keys'][] = "$year-$formattedMonth";
                        if ($month == 12) {
                            $tempArr['start'] = $year . '-' . $month;
                            $tempArr['end'] = $year . '-' . $month;
                        } else {
                            if ($month < 10) {
                                $month = '0' . $month;
                            }
                            $tempArr['start'] = $year . '-' . $month;
                            $tempArr['end'] = $year . '-' . ($month + 1);
                        }
                        $tempArr['power'] = 0;
                        foreach ($devices as $v) {
                            $deviceId = $v['id'];
                            $cacheKey1 = str_replace('-', "", $tempArr['start']);
                            $cacheKey = str_replace(' ', "", $cacheKey1);
                            $key = $deviceId . '-' . $cacheKey;
                            if (Redis::exists($key)) {
                                $tempPower = Redis::get($key);
                                if ($tempPower) {
                                    $tempArr['power'] += $tempPower / 1000;
                                    $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                                }
                            }
                        }
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                        $data['now_total'] += (float)$tempArr['power'];
                    }
                }
            } else {
                $contract = Contract::where('mobile', $user->mobile)
                    ->where('status', 20)
                    ->first();
                if (!$contract) {
                    return Result::error(1001, '暂无租房信息');
                }
                $deviceId = Device::where('house_id', $contract->house_id)->value('id');
                $startYear = 2023;
                $nowYear = date('Y');
                for ($l = $startYear; $l <= $nowYear; $l++) {
                    for ($m = 1; $m < 13; $m++) {
                        if ($m == 12) {
                            $startAll = $l . '-' . $m;
                        } else {
                            if ($m < 10) {
                                $m = '0' . $m;
                            }
                            $startAll = $l . '-' . $m;
                        }
                        $cacheKey1 = str_replace('-', "", $startAll);
                        $cacheKey = str_replace(' ', "", $cacheKey1);
                        $key = $deviceId . '-' . $cacheKey;
                        if (Redis::exists($key)) {
                            $tempPower = Redis::get($key);
                            if ($tempPower) {
                                $data['all'] += $tempPower;
                            }
                        }
                    }
                }
                if ($type == 'day') {
                    if ($time) {
                        $now = new \DateTime($time);
                    } else {
                        $now = new \DateTime();
                    }
                    $startOfDay = clone $now;
                    $startOfDay->setTime(0, 0, 0);
                    $now->setTime(23, 59, 59);
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($startOfDay <= $now) {
                        if ($i > 24) {
                            break;
                        }
                        // 将当前小时的时间添加到数组中
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H');
                        // 移动到下一个小时
                        $tempArr['end'] = $startOfDay->modify('+1 hour');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d H');

                        $cacheKey1 = str_replace('-', "", $tempArr['start']);
                        $cacheKey = str_replace(' ', "", $cacheKey1);
                        $key = $deviceId . '-' . $cacheKey;
                        if (Redis::exists($key)) {
                            $tempArr['power'] = Redis::get($key);
                            $tempArr['power'] = $data['data'][] = $tempArr['power'] / 1000;
                            $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                            $data['table'][] = $tempArr;
                        } else {
                            $tempArr['power'] = 0;
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += (float)$tempArr['power'];
                        $i++;
                    }
                } elseif ($type == 'month') {
                    if ($time) {
                        $dateStart = new \DateTime($time . "-01");
                    } else {
                        $dateStart = new \DateTime(date('Y-m') . "-01");
                    }
                    $dateEnd = (clone $dateStart)->modify('first day of next month');
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($dateStart < $dateEnd) {
                        if ($i > 31) {
                            break;
                        }
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                        $tempArr['end'] = $dateStart->modify('+1 day');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d');

                        $cacheKey1 = str_replace('-', "", $tempArr['start']);
                        $cacheKey = str_replace(' ', "", $cacheKey1);
                        $key = $deviceId . '-' . $cacheKey;
                        if (Redis::exists($key)) {
                            $tempArr['power'] = Redis::get($key);
                            $tempArr['power'] = $data['data'][] = $tempArr['power'] / 1000;
                            $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                            $data['table'][] = $tempArr;
                        } else {
                            $tempArr['power'] = 0;
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += (float)$tempArr['power'];
                        $i++;
                    }
                } else {
                    if ($time) {
                        $year = $time;
                    } else {
                        $year = date('Y');
                    }
                    $data['now_total'] = 0;
                    for ($month = 1; $month <= 12; $month++) {
                        // 使用 str_pad() 确保月份有两位数字
                        $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                        $tempArr = [];
                        $data['keys'][] = "$year-$formattedMonth";

                        if ($month == 12) {
                            $tempArr['start'] = $year . '-' . $month;
                            $tempArr['end'] = $year . '-' . $month;
                        } else {
                            if ($month < 10) {
                                $month = '0' . $month;
                            }
                            $tempArr['start'] = $year . '-' . $month;
                            $tempArr['end'] = $year . '-' . ($month + 1);
                        }
                        $cacheKey1 = str_replace('-', "", $tempArr['start']);
                        $cacheKey = str_replace(' ', "", $cacheKey1);
                        $key = $deviceId . '-' . $cacheKey;
                        if (Redis::exists($key)) {
                            $tempArr['power'] = Redis::get($key);
                            $tempArr['power'] = $data['data'][] = $tempArr['power'] / 1000;
                            $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                            $tempArr['power'] = 0;
                        }

                        $data['now_total'] += (float)$tempArr['power'];
                    }
                }
            }
        } else {
            $startYear = 2023;
            $nowYear = date('Y');
            for ($l = $startYear; $l <= $nowYear; $l++) {
                for ($m = 1; $m < 13; $m++) {
                    if ($m == 12) {
                        $startAll = $l . '-' . $m;
                    } else {
                        if ($m < 10) {
                            $m = '0' . $m;
                        }
                        $startAll = $l . '-' . $m;
                    }
                    $cacheKey1 = str_replace('-', "", $startAll);
                    $cacheKey = str_replace(' ', "", $cacheKey1);
                    $key = $deviceId . '-' . $cacheKey;

                    if (Redis::exists($key)) {
                        $tempPower = Redis::get($key);
                        if ($tempPower) {
                            $data['all'] += $tempPower;
                        }
                    }
                }
            }
            if ($type == 'day') {
                if ($time) {
                    $now = new \DateTime($time);
                } else {
                    $now = new \DateTime();
                }
                $startOfDay = clone $now;
                $startOfDay->setTime(0, 0, 0);
                $now->setTime(23, 59, 59);
                $i = 0;
                $data['now_total'] = 0;
                while ($startOfDay <= $now) {
                    if ($i > 24) {
                        break;
                    }
                    // 将当前小时的时间添加到数组中
                    $tempArr = [];
                    $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H');
                    // 移动到下一个小时
                    $tempArr['end'] = $startOfDay->modify('+1 hour');
                    $tempArr['end'] = $tempArr['end']->format('Y-m-d H');
                    $cacheKey1 = str_replace('-', "", $tempArr['start']);
                    $cacheKey = str_replace(' ', "", $cacheKey1);
                    $key = $deviceId . '-' . $cacheKey;
                    if (Redis::exists($key)) {
                        $tempArr['power'] = Redis::get($key);
                        $tempArr['power'] = $data['data'][] = $tempArr['power'] / 1000;
                        $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                        $data['table'][] = $tempArr;
                    } else {
                        $tempArr['power'] = 0;
                        $data['data'][] = 0;
                    }
                    $data['now_total'] += (float)$tempArr['power'];
                    $i++;
                }
            } elseif ($type == 'month') {
                if ($time) {
                    $dateStart = new \DateTime($time . "-01");
                } else {
                    $dateStart = new \DateTime(date('Y-m') . "-01");
                }
                $dateEnd = (clone $dateStart)->modify('first day of next month');
                $i = 0;
                $data['now_total'] = 0;
                while ($dateStart < $dateEnd) {
                    if ($i > 31) {
                        break;
                    }
                    $tempArr = [];
                    $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                    $tempArr['end'] = $dateStart->modify('+1 day');
                    $tempArr['end'] = $tempArr['end']->format('Y-m-d');
                    $cacheKey1 = str_replace('-', "", $tempArr['start']);
                    $cacheKey = str_replace(' ', "", $cacheKey1);
                    $key = $deviceId . '-' . $cacheKey;
                    if (Redis::exists($key)) {
                        $tempArr['power'] = Redis::get($key);
                        $tempArr['power'] = $data['data'][] = $tempArr['power'] / 1000;
                        $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                        $data['table'][] = $tempArr;
                    } else {
                        $tempArr['power'] = 0;
                        $data['data'][] = 0;
                    }
                    $data['now_total'] += (float)$tempArr['power'];
                    $i++;
                }
            } else {
                if ($time) {
                    $year = $time;
                } else {
                    $year = date('Y');
                }
                $data['now_total'] = 0;
                for ($month = 1; $month <= 12; $month++) {
                    // 使用 str_pad() 确保月份有两位数字
                    $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                    $tempArr = [];
                    $data['keys'][] = "$year-$formattedMonth";

                    if ($month == 12) {
                        $tempArr['start'] = $year . '-' . $month;
                        $tempArr['end'] = $year . '-' . $month;
                    } else {
                        if ($month < 10) {
                            $month = '0' . $month;
                        }
                        $tempArr['start'] = $year . '-' . $month;
                        $tempArr['end'] = $year . '-' . ($month + 1);
                    }
                    $cacheKey1 = str_replace('-', "", $tempArr['start']);
                    $cacheKey = str_replace(' ', "", $cacheKey1);
                    $key = $deviceId . '-' . $cacheKey;
                    if (Redis::exists($key)) {
                        $tempArr['power'] = Redis::get($key);
                        $tempArr['power'] = $data['data'][] = $tempArr['power'] / 1000;
                        $tempArr['power'] = number_format($tempArr['power'], 3, '.', '');
                        $data['table'][] = $tempArr;
                    } else {
                        $data['data'][] = 0;
                        $tempArr['power'] = 0;
                    }

                    $data['now_total'] += (float)$tempArr['power'];
                }
            }
        }
        $data['now_total'] = (float)$data['now_total'];
        return Result::success($data);
    }


    public function deviceCount()
    {
        $user = Token::getUser();
        if ($user->type == 'business') {
            $bussId = Business::where('user_id', $user->id)->value('id');
            $devices = Device::where('business_id', $bussId)
                ->whereNull('deleted_at')->get(['id']);
            $device = [];
            foreach ($devices as $v) {
                $device[] = $v['id'];
            }

            $data['all'] = Device::where('business_id', $bussId)->count();
            $data['online'] = Device::where('business_id', $bussId)
                ->where('online_status', 1)
                ->count();
            $data['off'] = Device::where('business_id', $bussId)
                ->where('online_status', 2)
                ->count();
            $data['warning'] = Device::where('business_id', $bussId)
                ->where('is_warning', 1)
                ->count();
            $data['low'] = Device::where('business_id', $bussId)
                ->whereColumn('low', '>=', 'du')
                ->count();
        } else {
            if ($user->type == 'admin') {
                $houses = House::query()->whereIn('house_class_id', json_decode($user->class_id))->pluck('id')->toArray();
                if (!$houses) {
                    $houses = [];
                }
                $data['all'] = Device::whereIn('house_id', $houses)->count();
                $data['online'] = Device::whereIn('house_id', $houses)
                    ->where('online_status', 1)
                    ->count();
                $data['off'] = Device::whereIn('house_id', $houses)
                    ->where('online_status', 2)
                    ->count();
                $data['warning'] = Device::whereIn('house_id', $houses)
                    ->where('is_warning', 1)
                    ->count();
                $data['low'] = Device::whereIn('house_id', $houses)
                    ->whereColumn('low', '>=', 'du')
                    ->count();

            } else {
                $data = [];
            }
        }
        return Result::success($data);
    }
}
